<script setup lang='ts'>
import { ref, onMounted, watch, computed } from "vue"
import { getBookChapterList } from "@/api/index"
import { useRouter } from "vue-router";
import { showConfirmDialog, showFailToast, showSuccessToast } from 'vant';

const bookInfo = ref<any>(null)
const $router = useRouter()
const chapterBuyChoose = ref<any>([])
const querys = $router.currentRoute.value.query
const localChapterBuy = ref<any>(JSON.parse(`${localStorage.getItem('chapter-buy')}`) || [])
const currentChapterBuy = ref<any>(null)
onMounted(async () => {

    //找到本地已购买书籍的索引
    currentChapterBuy.value = localChapterBuy.value.findIndex((o: any) => o.book == querys.tocId)

    //找到本地记录的购买的最后一章，下一次购买需要从下一章开始
    let f = localChapterBuy.value[currentChapterBuy.value]?.chapters[localChapterBuy.value[currentChapterBuy.value].chapters.length - 1]

    let chapterRes = await getBookChapterList($router.currentRoute.value.query.tocId)
    bookInfo.value = chapterRes.data.data
    let index;
    console.log(f);

    //如果有记录的这个索引，就是更新开始下载的索引，不然就是从需要付费的第一章开始
    if (f) {
        index = bookInfo.value.catalog.findIndex((o: any) => o.uuid == f?.uuid) + 1
    } else {
        index = bookInfo.value.catalog.findIndex((o: any) => o.needPay)
    }

    console.log(index);


    //将所有章节分成5挡购买
    let firstChoose = {
        number: 1,
        list: [...bookInfo.value.catalog.slice(index, index + 1)],
        price: totalPrice([...bookInfo.value.catalog.slice(index, index + 1)])
    }
    let secondChoose = {
        number: 20,
        list: [...bookInfo.value.catalog.slice(index, index + 20)],
        price: totalPrice([...bookInfo.value.catalog.slice(index, index + 20)])
    }
    let thirdChoose = {
        number: 50,
        list: [...bookInfo.value.catalog.slice(index, index + 50)],
        price: totalPrice([...bookInfo.value.catalog.slice(index, index + 50)])
    }
    let fourthChoose = {
        number: 100,
        list: [...bookInfo.value.catalog.slice(index, index + 100)],
        price: totalPrice([...bookInfo.value.catalog.slice(index, index + 100)])
    }
    let fifChoose = {
        number: bookInfo.value.catalog.slice(index,).length,
        list: bookInfo.value.catalog.slice(index,),
        price: totalPrice([...bookInfo.value.catalog.slice(index,)])
    }
    chapterBuyChoose.value = [fifChoose, fourthChoose, thirdChoose, secondChoose, firstChoose]
})

const totalPrice = (arr: any) => {
    //计算阅点
    let total = 0;
    arr.forEach((o: any) => {
        total += o.price
    })
    return total
}

const chooseIndex = ref<any>(0)

const toBuyChapter = () => {
    showConfirmDialog({
        title: '购买',
        message:
            '确认购买章节？',
    })
        .then(() => {
            if (currentChapterBuy.value != -1) {

                //购买章节拼合
                localChapterBuy.value[currentChapterBuy.value].chapters = [...localChapterBuy.value[currentChapterBuy.value].chapters, ...chapterBuyChoose.value[chooseIndex.value].list]

                localStorage.setItem('chapter-buy', JSON.stringify([...localChapterBuy.value]))
            } else {
                let obj = {
                    author: bookInfo.value.book.author,
                    book: bookInfo.value.book.sourceUuid,
                    chapters: [...chapterBuyChoose.value[chooseIndex.value].list],
                    title: bookInfo.value?.book?.title,
                    img: bookInfo.value.book.coverImage,
                }

                localStorage.setItem('chapter-buy', JSON.stringify([obj, ...localChapterBuy.value]))
            }
            showSuccessToast('购买成功！')
            setTimeout(() => {
                $router.back()
            }, 1000)
        })
        .catch(() => {
            showFailToast('取消购买！')
        });




}
</script>

<template>
    <div class="buy" v-if="bookInfo">
        <div class="title">
            <img src="@/assets/imgs/返回1.png" alt="" @click="$router.back()">
            <span>章节购买</span>
            <span></span>
        </div>
        <div class="buy-content">
            <p>{{ bookInfo.book?.title }}</p>
            <ul class="list">
                <li v-for="c, index in chapterBuyChoose" :key="index" :class="{ active: chooseIndex == index }"
                    @click="chooseIndex = index">
                    <div class="left">
                        <p v-if="index == 0">购买全部已出章节</p>
                        <p v-if="index != 0">购买{{ c.number }}章节</p>
                        <span v-if="index != 0">从{{ c.list[0]?.title }}</span>
                    </div>
                    <span>{{ c.price }}阅点</span>
                    <div class="check" v-show="chooseIndex == index">
                        <img src="@/assets/imgs/勾选.png" alt="">
                    </div>
                </li>
            </ul>
        </div>
        <div class="buy-action">
            <span>余额：无限阅点</span>
            <button @click="toBuyChapter">购买</button>
        </div>

    </div>
</template>

<style lang="less" scoped>
.buy {
    width: 100vw;
    height: 100vh;
    background-color: rgb(247, 247, 247);
    display: flex;
    flex-direction: column;

    .title {
        display: flex;
        height: 50rem;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #eee;

        img {
            width: 30rem;
            height: 30rem;
        }

        span {
            font-size: 17rem;
            color: #333;
        }

    }

    .buy-action {
        width: 100%;
        height: 200rem;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding-top: 30rem;

        >span {
            margin-bottom: 10rem;
        }

        button {
            width: 80%;
            border: none;
            height: 40rem;
            background-color: #fc1c1c;
            color: #fff;
            font-size: 17rem;
            border-radius: 20rem;
        }

    }

    .buy-content {
        flex-grow: 1;
        padding: 20rem 10rem 10rem;
        overflow: hidden;

        >p {
            color: #333;
            font-weight: 500;
            font-size: 24rem;
            margin-bottom: 10rem;
        }

        ul.list {
            height: 90%;
            overflow: auto;
            box-sizing: border-box;

            li {
                display: flex;
                justify-content: space-between;
                align-items: center;
                background-color: #fff;
                margin-bottom: 15rem;
                padding: 20rem 10rem;
                height: 93rem;
                border: 1rem solid #fff;
                box-sizing: border-box;
                box-shadow: 0 2rem 4rem 2rem #eee;
                position: relative;

                &.active {
                    border: 1rem solid #fc1c1c;
                }

                .left {
                    p {
                        font-size: 17rem;
                        font-weight: bold;
                    }

                    span {
                        color: #888;
                        font-size: 12rem;
                    }
                }

                >span {
                    color: #fc1c1c;
                    font-size: 17rem;
                }

                .check {
                    position: absolute;
                    bottom: 0;
                    right: 0;

                    img {
                        width: 40rem;
                    }
                }
            }
        }
    }


}
</style>
